import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.lang.Runnable;

public class TestProductorAndConsumer {

    public static void main(String[] args) throws IOException {
        List eggs = new ArrayList();
        Thread p1 = new Thread(new Productor(eggs), "p1");
        Thread p2 = new Thread(new Productor(eggs), "p2");
        Thread c1 = new Thread(new Consumer(eggs), "c1");
        Thread c2 = new Thread(new Consumer(eggs), "c2");
        p1.start();
        p2.start();
        c1.start();
        c2.start();
    }
}

class Productor implements Runnable {
    private List eggs;

    public Productor(List eggs) {
        this.eggs = eggs;
    }

    public void run() {
        synchronized (eggs) {
            for (int i = 0; i < 1000; i++) {
                while (eggs.size() >= 1000) {
                    try {
                        eggs.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(this + "生产鸡蛋！");
                eggs.add(1);
                eggs.notify();
            }
        }
    }

}

class Consumer implements Runnable {
    private List eggs;

    public Consumer(List eggs) {
        this.eggs = eggs;
    }

    @Override
    public void run() {
        synchronized (eggs) {
            for (int i = 0; i < 1000; i++) {
                while (eggs.size() <= 0) {
                    try {
                        eggs.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                // System.out.println(this+"消费鸡蛋！");
                eggs.remove(0);
                eggs.notify();
            }
        }
    }
}
